package com.itgacl.magic4j.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.itgacl.magic4j.common.context.RequestContext;
import com.itgacl.magic4j.libcommon.component.license.LicenseConstants;
import com.itgacl.magic4j.libcommon.component.license.service.LicenseService;
import com.itgacl.magic4j.libcommon.constant.HttpStatus;
import com.itgacl.magic4j.libcommon.exception.Magic4jException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局拦截器
 */
@Slf4j
@Component
public class GlobalInterceptor extends HandlerInterceptorAdapter {

    @Value("${magic4j.license.openCheck}")
    private Boolean licenseCheck;

    @Autowired
    private LicenseService licenseService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(licenseCheck){//开启了license校验
            validateLicense();
        }
        String client = request.getHeader("client");
        if(StrUtil.isNotBlank(client)){
            RequestContext.set(client);//存储到ThreadLocal，利用ThreadLocal管理登录用户信息实现随用随取
        }
        return super.preHandle(request, response, handler);
    }

    /**
     * 校验License
     */
    private void validateLicense() {
        int licenseState = licenseService.licenseCheck();
        switch (licenseState) {
            case LicenseConstants.STATE_FAILD:
                throw new Magic4jException("License无效或文件错误，无法使用服务", HttpStatus.FORBIDDEN);
            case LicenseConstants.STATE_TIMEOUT:
                throw new Magic4jException("License已经过期，无法再继续使用服务", HttpStatus.FORBIDDEN);
            case LicenseConstants.STATE_CODE_FROZEN:
                throw new Magic4jException("License已经被禁用，无法再继续使用服务", HttpStatus.FORBIDDEN);
            case LicenseConstants.STATE_CODE_ERR:
                throw new Magic4jException("License信息无效，无法使用服务", HttpStatus.FORBIDDEN);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        RequestContext.remove();//使用完ThreadLocal变量用threadLocal.remove()来手动清除，防止内存泄露
        super.afterCompletion(request, response, handler, ex);
    }
}
